package com.woniu.config;

import com.woniu.filter.JwtTokenAuthenticationFilter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

//@Controller
@EnableWebSecurity //开启安全认证策略，同时加载了AuthenticationConfiguration 配置了认证信息
@EnableGlobalMethodSecurity(prePostEnabled=true) //开启 判断用户对某个控制层的方法是否具有访问权限
// 提供三种机制来鉴权 prePostEnabled 、securedEnabled 和 jsr250Enabled
public class MyWebSecurity extends WebSecurityConfigurerAdapter {
    @Autowired
    private JwtTokenAuthenticationFilter jwtTokenAuthenticationFilter;

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.GET,
                "/v2/**",
                "/swagger-resources/**",
                "/configuration/**",
                "/swagger-ui.html/**",
                "/webjars/**",
                "img.icons/**",
                "/doc.html",
                "/home",
                "/customer/receiveCoupon");
        super.configure(web);
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //http.httpBasic().and().authorizeRequests().anyRequest().authenticated(); //关闭httpBasic认证
        //需要放行的url在这里配置,必须要放行/login和/login.html,不然会报错
        //"/doc.html","/webjars/**","/img.icons/**","/swagger-resources/**","/**","/v2/api-docs",
        http.authorizeRequests().antMatchers(
                "/doc.html", "/v2/**",
                "/swagger-resources/**",
                "/configuration/**",
                "/swagger-ui.html/**",
                "/webjars/**",
                "img.icons/**",
                "/doc.html",
                "/home",
                "/customer/receiveCoupon")
                .permitAll().anyRequest().authenticated().and()
                .addFilterBefore(jwtTokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        //关闭CSRF跨域
        http.csrf().disable();
        //关闭session最严格的策略
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}